package fatworm.query.expression;

import fatworm.query.Plan;
import fatworm.query.Scan;
import fatworm.storage.table.Schema;

public class ExistsTerm implements Term {
	
	private Expression exp;
	
	public ExistsTerm(Expression exp) {
		this.exp = exp;
	}
	
	public boolean isOK(Scan s) {
		Scan subs = exp.asSubquery().open();
		subs.beforeFirst();
		
		if (subs.next())
			return true;
		else
			return false;
	}
	
	public boolean isIn(Schema sch) {
		return exp.isIn(sch);
	}
	
	public int reductionFactor(Plan p) {
		if (isOK(p.open()))
			return p.recordsOutput();
		else
			return Integer.MAX_VALUE;
	}
	
	public String toString() {
		return "EXISTS " + exp.toString();
	}
}